﻿using Blog.webapi.Utility.ApiResult;
using EiiFBlog.IServer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Blog.webapi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class TypeController : ControllerBase
    {
        private readonly ITypeService _typeService;
        public TypeController(ITypeService typeService)
        {
            this._typeService = typeService;
        }

        [HttpGet("Types")]
        public async Task<ApiResult> GetTypes()
        {
            var types = await _typeService.Query();
            if (types.Count == 0) return ApiResultHelper.Error("类型为空，请先添加类型");
            return ApiResultHelper.Success(types);
        }

        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name)
        {
            EiiF_Blog.Type type = new EiiF_Blog.Type
            {
                Name = name,
            };
            bool a = await _typeService.Create(type);
            if (a)
            {
                return ApiResultHelper.Success(type);
            }
            else
            {
                return ApiResultHelper.Error("添加失败");
            }
        }

        [HttpPut("Edit")]
        public async Task<ActionResult<ApiResult>> Edit(int id,string name)
        {
            var type = await _typeService.Find(id);
            if (type == null) return ApiResultHelper.Error("没有该类型");
            type.Name = name;
            bool c = await _typeService.Edit(type);
            if (c)
            {
                return ApiResultHelper.Success(type);
            }
            else
            {
                return ApiResultHelper.Error("修改失败");
            }
        }

        [HttpDelete("Delete")]
        public async Task<ActionResult<ApiResult>> Delete(int id)
        {
            bool b = await _typeService.Delete(id);
            if (b)
            {
                return ApiResultHelper.Success(b);
            }
            else
            {
                return ApiResultHelper.Error("删除失败");
            }
        }
    }
}
